package StudyCode.summary.aclfile;

import java.io.*;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class First400PrimeNumbers {
	public static void main(String[] arguments) {
		write();
		read();
	}

	private static boolean isPrime(int checkNumber) {
		double root = Math.sqrt(checkNumber);
		for (int i = 2; i <= root; i++) {
			if (checkNumber % i == 0)
				return false;
		}
		return true;
	}

	private static void write() {
		int[] primes = new int[400];
		int numPrimes = 0;
		int candidate = 2;
		while (numPrimes < 400) {
			if (isPrime(candidate)) {
				primes[numPrimes] = candidate;
				numPrimes++;
			}
			candidate++;
		}

		try (
				FileOutputStream file = new FileOutputStream("400primes.dat");
				BufferedOutputStream buff = new BufferedOutputStream(file);
				DataOutputStream data = new DataOutputStream(buff);) {

			for (int i = 0; i < 400; i++)
				data.writeInt(primes[i]);
			data.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void read() {
		try (FileInputStream file = new FileInputStream("400primes.dat");
		     BufferedInputStream buff = new BufferedInputStream(file);
		     DataInputStream data = new DataInputStream(buff)) {

			try {
				while (true) {
					int in = data.readInt();
					System.out.print(in + " ");
				}
			} catch (EOFException eof) {
				buff.close();
			}
		} catch (IOException e) {
			System.out.println("Error - " + e.toString());
		}
	}
}
